package ToDoList;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.net.URI;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Optional;

@RestController
public class TaskController {
    @Autowired
    private TaskRepository taskRepository;

    @PostMapping("/tasks")
    public ResponseEntity<String> add(@RequestBody Task request) {
        if (request.getTitle() == null) {
            return ResponseEntity.badRequest().body("No data required");
        }

        Task task = taskRepository.save(new Task(request.getTitle(), request.getDescription()));

        return ResponseEntity.created(URI.create("/tasks/" + task.getId())).build();
    }

    @GetMapping("/tasks/{id}")
    public ResponseEntity<Task> get(@PathVariable Integer id) {
        Optional<Task> optionalTask = taskRepository.findById(id);

        if (optionalTask.isEmpty()) {
            return ResponseEntity.notFound().build();
        }

        return ResponseEntity.ok(optionalTask.get());
    }

    @GetMapping("/tasks")
    public ResponseEntity<Collection<Task>> list() {
        Collection<Task> list = new ArrayList<>();
        taskRepository.findAll().forEach(list::add);

        return ResponseEntity.ok(list);
    }

    @PatchMapping("/tasks/{id}")
    public ResponseEntity<String> set(@PathVariable Integer id, @RequestBody Task request) {
        Optional<Task> optionalTask = taskRepository.findById(id);

        if (optionalTask.isEmpty()) {
            return ResponseEntity.notFound().build();
        }

        Task task = optionalTask.get();
        boolean changed = false;

        if (request.getIsDone() != null && !request.getIsDone().equals(task.getIsDone())) {
            task.setIsDone(request.getIsDone());
            changed = true;
        }

        if (request.getTitle() != null && !request.getTitle().equals(task.getTitle())) {
            task.setTitle(request.getTitle());
            changed = true;
        }

        if (request.getDescription() != null && !request.getDescription().equals(task.getDescription())) {
            task.setDescription(request.getDescription());
            changed = true;
        }

        if (changed) {
            taskRepository.save(task);

            return ResponseEntity.ok().build();
        }

        return ResponseEntity.unprocessableEntity().body("No data to change");
    }

    @DeleteMapping("/tasks/{id}")
    public ResponseEntity<String> delete(@PathVariable Integer id) {
        Optional<Task> optionalTask = taskRepository.findById(id);

        if (optionalTask.isEmpty()) {
            return ResponseEntity.notFound().build();
        }

        taskRepository.delete(optionalTask.get());

        return ResponseEntity.ok().build();
    }
}
